import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import './cloth.dart';
import './wardrobe.dart';


class DatabaseHelper {
  static final _databaseName = "wardrobe_database.db";
  static final _databaseVersion = 1;

  static Database? _database;

  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion, onCreate: _onCreate);
  }

  Future<void> _onCreate(Database db, int version) async {
    await db.execute("""
      CREATE TABLE Wardrobe (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        wardrobename TEXT
      )
    """);
    await db.execute("""
      CREATE TABLE Cloth (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        clothname TEXT,
        clothbelong TEXT,
        clothclass TEXT,
        wardrobeId INTEGER,
        FOREIGN KEY(wardrobeId) REFERENCES Wardrobe(id)
      )
    """);
  }

  // 插入衣柜数据
  Future<int> insertWardrobe(Wardrobe wardrobe) async {
    Database db = await instance.database;
    return await db.insert('Wardrobe', wardrobe.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  // 插入衣物数据
  Future<int> insertCloth(Cloth cloth) async {
    Database db = await instance.database;
    return await db.insert('Cloth', cloth.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  // 查询衣柜下的所有衣物
  Future<List<Cloth>> getClothesByWardrobe(int wardrobeId) async {
    Database db = await instance.database;
    List<Map<String, dynamic>> maps = await db.query(
      'Cloth',
      where: 'wardrobeId = ?',
      whereArgs: [wardrobeId],
    );
    return List.generate(maps.length, (i) {
      return Cloth(
        id: maps[i]['id'],
        clothname: maps[i]['clothname'],
        clothbelong: maps[i]['clothbelong'],
        clothclass: maps[i]['clothclass'],
        wardrobeId: maps[i]['wardrobeId'],
      );
    });
  }

  // 更多查询和操作方法...
}
